define(["jquery", "template", "bootstrap", "bbcare", "jquery.dataTables", 'bootstrap.dataTables',
    "scprit/department/view/template/follow-up/common.js",
    "oms_config/root"
], function ($, template, bootstrap, $bb, $jTable, $bTable, $common, $root) {
    var tables = {}
    tables.init = function (type) {
        var URL = $bb.baseUrl("department") + "followup/service"
        var sessionId = sessionStorage.sessionId
        var oTable = $("#myEduTable").DataTable({
            pageLength: 10, //默认条数
            lengthMenu: [10, 30, 60], //每页显示记录数options选项
            info: true, //是否使用表格左下角的信息；
            destroy: true,
            stateSave: false,
            ordering: false, //是否允许Datatables开启排序
            paging: true, //默认true ,开启分页
            searching: false, //默认true,是否开启搜索
            serverSide: true, //是否启用服务器端处理模式，false,在客户端处理，true在服务器端处理；
            ajax: {
                url: URL + "/patient/evaluation/patientListqry?sessionId=" + sessionId,
                type: "post",
                contentType: "application/json;charset=UTF-8",
                dataType: "json",
                data: function (args) {
                    var config = $root.init()
                    var showFlag = config.dom.baileyScreeningShowCreate ? "1" : "0"
                    var data = JSON.stringify({
                        data: {
                            "args": JSON.stringify(args),
                            'examinationPaperName': type,
                            'phoneNum': $.trim($("#phoneNum").val()),
                            'patientName': $.trim($("#patientName").val()),
                            'showFlag': showFlag
                        }
                    })
                    return data
                },
                dataSrc: function (data) {
                    if (data.rows == 0) {
                        var phone = $.trim($("#phoneNum").val())
                        var name = $.trim($("#patientName").val())
                        if (phone) { $("#newTel").addClass("show") }
                        if (name) { $("#newName").addClass("show") }
                    } else {
                        $(".new").removeClass("show")
                    }
                    return data.rows
                }
            },
            columns: [{
                data: 'userName',
                defaultContent: ""
            },
            {
                data: function (row, type, set, meta) {
                    var nowDate = $common.getNowFormatDate()
                    var diff = $common.DateDiff(nowDate, row.birthday)
                    var monthAge = $common.monthAge(diff, row.pregnancDay)
                    return monthAge.toFixed(1)
                },
                defaultContent: ""
            },
            {
                data: function (row, type, set, meta) {
                    return row.weight ? row.weight : "未知"
                },
                defaultContent: ""
            },
            {
                data: function (row, type, set, meta) {
                    return 37 * 7 > row.pregnancDay * 1 ? "是" : "否"
                },
                defaultContent: ""
            },
            {
                data: function (row, type, set, meta) {
                    var nowDate = $common.getNowFormatDate()
                    var acturalDay = $common.DateDiff(nowDate, row.birthday)
                    return $common.age(acturalDay, row.pregnancDay)
                },
                defaultContent: ""
            },
            {
                data: function (row, type, set, meta) {
                    return row.delivery ? row.delivery : "未知"
                },
                defaultContent: ""
            },
            {
                data: function (row, type, set, meta) {
                    return row.outpatient ? row.outpatient : "未知"
                },
                defaultContent: ""
            },
            {
                data: function (row, type, set, meta) {
                    return row.socialCard ? row.socialCard : "未知"
                },
                defaultContent: ""
            },
            {
                data: function (row, type, set, meta) {
                    return row.cardNo ? row.cardNo : "未知"
                },
                defaultContent: ""
            },
            {
                data: function (row, type, set, meta) {
                    let newEvaEle = ''
                    if (window.__config__.role.indexOf('ReadOnly') == -1) {
                        newEvaEle = '<a class="newEva">新建测评</a>'
                    } else {
                        newEvaEle = ''
                    }
                    return newEvaEle + '&nbsp;' +
                        '<a class="historyEva">历史测评</a>'
                },
                defaultContent: ""
            }
            ],
            rowCallback: function (row, data, index) {
                $('td:eq(9) a', row).click(function () {
                    var attr = $(this).attr("class")
                    var babyId = data.userId
                    var obj = {
                        "babyId": babyId,
                        "type": type
                    }
                    if (attr == "newEva") {
                        if (type == "Neuropsychology") {
                            $bb.openPage("childPsychologyReport", obj)
                        } else if (type == "BaileyScreening") {
                            var nowDate = $common.getNowFormatDate()
                            var diff = $common.DateDiff(nowDate, data.birthday)
                            var monthAge = $common.monthAge(diff, data.pregnancDay).toFixed(1)
                            if (monthAge > 0 && monthAge <= 42) {
                                $bb.openPage("baileyScreeningReport", obj)
                            } else {
                                $bb.toastShow("患者在0~42（大于0）月龄才可做贝利筛查测试！")
                            }
                        } else if (type == 'Gesell') {
                            $bb.openPage("gasellIntelligenceReport", obj)
                        } else if (type == "Temperament") {
                            $bb.openPage("temperamentReport", obj)
                        } else if (type == "nbna") {
                            $bb.openPage("nbnaReport", obj)
                        } else if (type == "SmallWechsler") {
                            obj.type = "Wechsler"
                            $bb.openPage("smallWechslerReport", obj)
                        }
                    } else if (attr == "historyEva") {
                        if (type == "SmallWechsler") {
                            obj.type = "Wechsler"
                        }
                        $bb.openPage("history", obj)
                    }
                })
            },
            initComplete: function (settings, json) {
                $("#phoneNum").on("input propertychange", function () {
                    var key = $(this).val()
                    var reg = /^[0-9]{0,11}$/
                    if (!reg.test(key)) {
                        $bb.toastShow("请输入11位手机号码", 1500)
                        $(this).val("").focus()
                    } else {
                        oTable.ajax.reload()
                    }
                })
                $("#patientName").on("input propertychange", function () {
                    oTable.ajax.reload()
                })
                $("#btnSearch").click(function () {
                    oTable.ajax.reload()
                })
            }
        })
        var id = "#search" + type
        $common.searchBoxInit({ "id": id })
        $('#myModal').on('hidden.bs.modal', function (e) {
            $("#searchUser").val("")
            $("#infoLists").removeClass("show").html("")
        })
        $("#searchUser").on("input propertychange", function () {
            var key = $.trim($(this).val())
            if (key) {
                search(key)
            } else {
                $("#infoLists").removeClass("show").html('')
            }
        })
        $("#toSearch").click(function () {
            var key = $.trim($("#searchUser").val())
            if (key) {
                search(key)
            } else {
                $("#infoLists").removeClass("show").html("")
            }
        })
        $("#newName").click(function () {
            var name = $.trim($("#patientName").val())
            $('#myModal').modal('show')
            $("#searchUser").val(name)
            search(name)
        })
        $("#newTel").click(function () {
            var phone = $.trim($("#phoneNum").val())
            $('#myModal').modal('show')
            $("#searchUser").val(phone)
            search(phone)
        })
        //输入内容先按照姓名查询，如果查询不到按照手机号查询: flag：手机号：1；不传：姓名；
        function search (key, flag) {
            var params = {}
            if (flag == "1") {
                params = {
                    "flag": 2,
                    "phoneNum": key
                }
            } else {
                params = {
                    "flag": 2,
                    "patientName": key
                }
            }
            $bb.ajax({
                url: URL + "/patient/patientQueueListQuery",
                data: JSON.stringify({
                    data: params
                }),
                success: function (data) {
                    if (data.success) {
                        if (data.data.rows.length > 0) {
                            $common.searchListInit({ "id": "#infoLists", "data": data.data.rows })
                        } else {
                            if (flag) {
                                $("#infoLists").html("该患者可能还没有建档")
                            }
                            if (!flag) {
                                search(key, "1")
                            }
                        }
                        $("#infoLists").addClass("show")
                        $("#infoLists").on("click", "li", function () {
                            var userId = $(this).attr("userId")
                            var obj = {
                                "babyId": userId,
                                "type": type
                            }
                            if (type == "Neuropsychology") {
                                $bb.openPage("childPsychologyReport", obj)
                            } else if (type == "BaileyScreening") {
                                var birth = $(this).attr("birthday")
                                var pregnancyDay = $(this).attr("pregnancyDay")
                                var nowDate = $common.getNowFormatDate()
                                var diff = $common.DateDiff(nowDate, birth)
                                var monthAge = $common.monthAge(diff, pregnancyDay).toFixed(1)
                                if (monthAge > 0 && monthAge <= 42) {
                                    $bb.openPage("baileyScreeningReport", obj)
                                } else {
                                    $bb.toastShow("患者在0~42（大于0）月龄才可做贝利筛查测试！")
                                }
                            } else if (type == 'Gesell') {
                                $bb.openPage("gasellIntelligenceReport", obj)
                            } else if (type == "Temperament") {
                                $bb.openPage("temperamentReport", obj)
                            } else if (type == "nbna") {
                                $bb.openPage("nbnaReport", obj)
                            } else if (type == "SmallWechsler") {
                                obj.type = "Wechsler"
                                $bb.openPage("smallWechslerReport", obj)
                            }
                        })
                    }
                }
            })
        }
    }

    return tables
})